package com.zsxb.crm.service.impl;

import com.zsxb.crm.dto.MenuPageDTO;
import com.zsxb.crm.mapper.MenuMapper;
import com.zsxb.crm.pojo.Menu;
import com.zsxb.crm.service.MenuService;
import com.zsxb.crm.vo.MenuTrees;
import com.zsxb.crm.vo.MenuVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuMapper menuMapper;

    /**
     * 菜单管理分页查询
     */
    @Override
    public List<Menu> queryAll(MenuPageDTO menuPageDTO) {
        return menuMapper.queryAll(menuPageDTO);
    }

    /**
     * 菜单栏新增
     */
    @Override
    public void insert(Menu menu) {
        menuMapper.add(menu);
    }

    /**
     * 菜单栏删除
     */
    @Override
    public void delete(Long menuId) {
        menuMapper.deleteByMenuId(menuId);
    }

    /**
     * 根据id查询菜单栏详情
     */
    @Override
    public MenuVO queryByMenuId(Long menuId) {
        return  menuMapper.queryByMenuId(menuId);
    }

    /**
     * 菜单修改
     */
    @Override
    public void update(Menu menu) {
        menuMapper.update(menu);
    }

    /**
     * 获取所有菜单的树形结构
     * @return
     */
    @Override
    public List<MenuTrees> roleMenuTreeselect() {
        List<MenuTrees> menuList = menuMapper.queryAllMenu();
        List<MenuTrees> menuVOS = treeselectVOList(menuList);
        return menuVOS;
    }

    public List<MenuTrees> treeselectVOList(List<MenuTrees> deptList){
        List<MenuTrees> resultJsonList = new ArrayList<>();
        deptList.forEach(d -> {
            if (d != null && d.getId() == 0) {
                resultJsonList.add(findChildren(d, deptList));
            }
        });
        return resultJsonList;
    }

    private MenuTrees findChildren(MenuTrees parent, List<MenuTrees> deptList) {
        List<MenuTrees> children = new ArrayList<>();
        deptList.forEach(d -> {
            if (d != null && parent.getId().equals(d.getParentId())) {
                children.add(findChildren(d, deptList));
            }
        });
        parent.setChildren(children);
        return parent;
    }
}
